﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;

namespace PM.PMSys
{
    /// <summary>
    ///权限操作类(authority)
    /// </summary>
    public class authority
    {
        public authority()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 获取所有用户类型的权限
        /// </summary>
        /// <param name="sqlstr">查询字符串</param>
        /// <returns>返回所有权限</returns>
        public DataTable GetAuthority(string sqlstr)
        {
            try
            {
                DataTable mydatatable = PM.Code.DAL.DbHelper.ExecuteDataTableBySql(sqlstr);
                return mydatatable;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// 获取某一个用户类型的权限
        /// </summary>
        /// <param name="sqlstr">用户类型ID</param>
        /// <returns>返回相应权限</returns>
        public string GetAuthorityById(string typeid)
        {
            string sqlstr = "";
            if (typeid != string.Empty)
                sqlstr = "select enablefun from Sys_UserType where typeid='" + typeid + "' and state='true'";
            try
            {
                object result = PM.Code.DAL.DbHelper.GetSingle(sqlstr);
                return result.ToString();
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        #region 生成权限表格（四张）已注释
        /// <summary>
        /// 生成权限表格（四张）
        /// </summary>
        /// <param name="values">权限值</param>
        /// <returns>返回四张表格（table源），用“|”隔开</returns>
        //public string CreateAuthorityTable(string values)
        //{
        //    string sqlstr = "select * from Sys_Menu order by menucode";
        //    DataTable dt_menu = PM.Code.DAL.DbHelper.ExecuteDataTableBySql(sqlstr);
        //    string[] funs = values.Split(new char[] { ',' });
        //    StringBuilder table = new StringBuilder();
        //    for (int i = 0; i < funs.Length-1; i++)
        //    {
        //        DataTable backup = dt_menu;
        //        if (funs[i] != "")
        //        {
        //            table.Append(BeginToDraw(funs[i], backup,i.ToString()));
        //            table.Append ("|");
        //        }
        //        else
        //            continue;
        //    }
        //    return table.ToString();
        //}
        #endregion 
        #region 生成权限表格（重载）
        /// <summary>
        /// 生成所有权限表格
        /// </summary>
        /// <param name="id">生成的表格的id</param>
        /// <returns>返回表格（无div）</returns>
        public string CreateAuthorityTable(string id)
        {
            StringBuilder table = new StringBuilder();
            string sqlstr = "select * from Sys_Menu order by menucode";
            DataTable dt_menu = PM.Code.DAL.DbHelper.ExecuteDataTableBySql(sqlstr);
            return table.Append(BeginToDraw("", dt_menu, id)).ToString();
        }
        /// <summary>
        /// 生成权限表格
        /// </summary>
        /// <param name="values">权限值</param>
        /// <param name="values">角色标记</param>
        /// <param name="values">角色名称</param>
        /// <returns>返回表格（有div）</returns>
        public string CreateAuthorityTable(string values,string id,string name)
        {
            StringBuilder table = new StringBuilder();
            table.AppendFormat("<div title='{0}' style='padding:10px;' id='{1}'>",name,id);
            if (values != "")
            {
                string sqlstr = "select * from Sys_Menu order by menucode";
                DataTable dt_menu = PM.Code.DAL.DbHelper.ExecuteDataTableBySql(sqlstr);
                //DataTable backup = dt_menu;
                table.Append(BeginToDraw(values, dt_menu, id));
                return table.Append("</div>").ToString();
            }
            else
                return table.Append("</div>").ToString();
        }
        /// <summary>
        /// 制作表格
        /// </summary>
        /// <param name="fun">默认功能</param>
        /// <param name="menu_fun">所有菜单</param>
        /// <param name="tableid">表格的id</param>
        /// <returns>返回表格</returns>
        protected string BeginToDraw(string fun,DataTable menu_fun,string tableid)
        {
            DataRow[] function=null;
            int tdcount = 0;
            int trcount = 0;
            StringBuilder table_n = new StringBuilder();
            if (fun != "")
            {
                if (fun == "|")
                    return "<table id=table" + tableid + "><tr><td>系统没有对该类型配备任何权限！</td></tr></table>";
                //产生筛选条件
                string funfilter = fun.Replace("|", " or menucode=");
                string temp = "hello" + funfilter;
                funfilter = temp.Replace("hello or ", "");
                table_n.AppendFormat("<table id='table{0}' class='authtable' cellspacing='0' cellpadding='0' border='0' style='width:80%'>", tableid);
                function = menu_fun.Select(funfilter);
            }
            else
            {
                table_n.AppendFormat("<table id='table{0}' cellspacing='0' cellpadding='0' border='0' style='width:100%'>", tableid);
                function = menu_fun.Select();
            }

            foreach (DataRow rows in function)
            {
                if (rows["menucode"].ToString().Length == 2 || tdcount >= 6)
                {
                    //增加新行
                    trcount += AddNewRow(ref table_n, tdcount);
                    tdcount = (rows["menucode"].ToString().Length == 2) ? 0 : 1;
                }
                //增加新单元格
                tdcount += AddNewCell(ref table_n,rows["menucode"].ToString(),rows["menuname"].ToString(),tdcount,tableid);
            }
            //最后未满的补上单元格
            for (int j = tdcount; j < 7; j+=2)
            {
                table_n.Append("<td class='authbottom'></td><td class='authbottom authright'></td>");
            }
            return table_n.Append("</tr></table>").ToString();
        }
        /// <summary>
        /// 添加新行
        /// </summary>
        /// <param name="table">源表</param>
        /// <param name="table">单元格数</param>
        /// <returns>返回增加的行数</returns>
        protected int AddNewRow(ref StringBuilder table_n,int td)
        {
            if (td >= 6)
            {
                table_n.Append("</tr><tr>");
                return 1;
            }
            else if (td != 0)
            {
                for (int i = td; i <7; i += 2)
                {
                    table_n.Append("<td class='authbottom'></td><td class='authbottom authright'></td>");
                }
                table_n.Append("</tr><tr>");
                return 1;
            }
            else
            {
                table_n.Append("<tr>");
                return 1;
            }
        }
        /// <summary>
        /// 增加单元格数
        /// </summary>
        /// <param name="table_n">源表</param>
        /// <param name="menucode">功能编码</param>
        /// <param name="menuname">功能名称</param>
        /// <param name="td">单元格数</param>
        /// <returns></returns>
        protected int AddNewCell(ref StringBuilder table_n,string menucode,string menuname,int td,string tablenum)
        {
            if (td >= 6||td==0)
            {
                table_n.AppendFormat("<td class='authbottom authright'><input type='checkbox' onclick='clickbycheckbox(this)' id='{1}_cb{0}'/>", menucode, tablenum);
                table_n.AppendFormat("<label id='label{0}' for='{2}_cb{0}' title='{1}'>{1}</label></td>", menucode, menuname,tablenum);
                td = 1;
            }
            else
            {
                table_n.AppendFormat("<td class='authbottom'><input type='checkbox' onclick='clickbycheckbox(this)' id='{1}_cb{0}'/></td>", menucode, tablenum);
                table_n.AppendFormat("<td class='authbottom authright'><label id='label{0}' for='{2}_cb{0}' title='{1}'>{1}</label></td>", menucode, menuname, tablenum);
                td = 2;
            }
            return td;
        }
        #endregion
        /// <summary>
        /// 更新一个角色的权限
        /// </summary>
        /// <param name="value">权限值</param>
        /// <param name="id">角色id</param>
        /// <returns>返回结果</returns>
        public int Update_Authority(string value,int id)
        {
            try
            {
                SqlParameter[] AuthSqlParameter ={ 
                new SqlParameter("@typeid",SqlDbType.Int),
                new SqlParameter("@funs",SqlDbType.NVarChar)};
                AuthSqlParameter[0].Value = id;
                AuthSqlParameter[1].Value = value;
                StringBuilder sqlstr = new StringBuilder("update Sys_UserType set enablefun=@funs where id=@typeid");
                sqlstr.Append(";select @@IDENTITY");
                return PM.Code.DAL.DbHelper.ExecuteSql(sqlstr.ToString(), AuthSqlParameter);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 更新一个角色的权限（越权配置）
        /// </summary>
        /// <param name="value">权限值</param>
        /// <param name="id">角色id（不是编号）</param>
        /// <returns>返回结果</returns>
        public int Update_Authority_Across(string value, int id)
        {
            try
            {
                SqlParameter[] AuthSqlParameter ={ 
                new SqlParameter("@typeid",SqlDbType.Int),
                new SqlParameter("@funs",SqlDbType.NVarChar)};
                AuthSqlParameter[0].Value = id;
                AuthSqlParameter[1].Value = value;
                StringBuilder sqlstr = new StringBuilder("update Sys_UserType set fun=@funs,enablefun=@funs where id=@typeid");
                return PM.Code.DAL.DbHelper.ExecuteSql(sqlstr.ToString(), AuthSqlParameter);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 更新一个角色的名称与编号
        /// </summary>
        /// <param name="rolename">角色名称</param>
        /// <param name="roleid">角色编号</param>
        /// <param name="id">角色id</param>
        /// <param name="status">启用/禁用</param>
        /// <returns>返回影响行数</returns>
        public int Update_Authority(string rolename, string roleid, int id,bool status)
        {
            try
            {
                SqlParameter[] AuthSqlParameter ={ 
                new SqlParameter("@id",SqlDbType.Int),
                new SqlParameter("@typename",SqlDbType.NVarChar),
                new SqlParameter("@typeid",SqlDbType.TinyInt),
                new SqlParameter("@state",SqlDbType.Bit)};
                AuthSqlParameter[0].Value = id;
                AuthSqlParameter[1].Value = rolename;
                AuthSqlParameter[2].Value = Int32.Parse(roleid);
                AuthSqlParameter[3].Value = status ? 1 : 0;
                StringBuilder sqlstr = new StringBuilder("update Sys_UserType set typename=@typename,typeid=@typeid,state=@state where id=@id");
                sqlstr.Append(";select @@IDENTITY");
                return PM.Code.DAL.DbHelper.ExecuteSql(sqlstr.ToString(), AuthSqlParameter);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 增加一个角色并赋予权限
        /// </summary>
        /// <param name="model">角色实体类</param>
        public int Insert_Authority(PM.Model.UserType model)
        {
            try
            {
                SqlParameter[] AuthSqlParameter ={ 
                new SqlParameter("@typename",model.TypeName),
                new SqlParameter("@typeid",model.TypeId),
                new SqlParameter("@rating",model.Rating),
                new SqlParameter("@state",model.State),
                new SqlParameter("@fun",model.Fun),
                new SqlParameter("@enablefun",model.EnableFun),
                new SqlParameter("@disablefun",model.DisableFun)};
                StringBuilder sqlstr = new StringBuilder("insert into Sys_UserType(");
                sqlstr.Append("typename,typeid,rating,state,fun,enablefun,disablefun)");
                sqlstr.Append(" values(");
                sqlstr.Append("@typename,@typeid,@rating,@state,@fun,@enablefun,@disablefun)");
                return PM.Code.DAL.DbHelper.ExecuteSql(sqlstr.ToString(), AuthSqlParameter);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 删除一个角色
        /// </summary>
        /// <param name="model">角色实体类</param>
        public int Delete_Authority(int id)
        {
            try
            {
                SqlParameter[] AuthSqlParameter ={ 
                new SqlParameter("@id",id)};
                StringBuilder sqlstr = new StringBuilder("delete Sys_UserType");
                sqlstr.Append(" where id=@id");
                return PM.Code.DAL.DbHelper.ExecuteSql(sqlstr.ToString(), AuthSqlParameter);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 检测角色编号有无重复
        /// </summary>
        /// <param name="roleid">角色编号</param>
        /// <returns>返回是/否（布尔）</returns>
        public bool CheckExist(int roleid)
        {
             SqlParameter[] AuthSqlParameter ={ 
             new SqlParameter("@typeid",SqlDbType.NVarChar)};
             string sqlstr = "select id from Sys_UserType where typeid=@typeid";
             return PM.Code.DAL.DbHelper.Exists(sqlstr,AuthSqlParameter);
        }
        /// <summary>
        /// 查找当前权限
        /// </summary>
        /// <param name="id">角色ID（非编号）</param>
        /// <returns></returns>
        public string getCurrentAuth(int id)
        {
            string sqlstr = "select fun from Sys_UserType where id=" + id.ToString();
            return PM.Code.DAL.DbHelper.GetSingle(sqlstr).ToString();
        }
    }
}
